import {get, getWithAuth} from './request';
import ProjectTable from '../tools/project-table';
var trustyTool  = require('../tools/trusty-tool');


let table  = new ProjectTable();

export async function queryProjectInfos(){
  if( table.isSynchronized == true ){
    return {status:200, data:table.projectInfos}
  }
  else{
    const url  = 'http://47.99.240.14:8086/projects';
    const result  = await getWithAuth(url);
    if(result.status == 200){
      const infos  = result.data.items;
      table.setProjectInfos(infos);
      table.isSynchronized  = true;
    }

    return result;
  }
}


export async function  queryTrustyOfProject(projectId){
  if( false === trustyTool.isTrustyOfProjectSynchronized(projectId) ){
    console.log(projectId, 'have not synchronized');
    const url  = 'http://47.99.240.14:8086/projects/'+projectId+'/trusty';
    const result  = await getWithAuth(url);
    if(200 === result.status){
      console.log('query trusty success', result);
      trustyTool.setTrustyOfProject(projectId, result.data.items);
      return {fresh:true , data:trustyTool.getTrustyIdListOfProject(projectId)};
    }
    else{
      return null;
    }
  }
  else{
      return {fresh:false , data:trustyTool.getTrustyIdListOfProject(projectId)};
  }
}


export async function queryTrustyLibraryInfos(){
  const url  = 'http://47.99.240.14:8086/users';

  const result  = await getWithAuth(url);

  if(200 == result.status){
    const trustyInfos  = result.data.items;

    trustyTool.resetTrusyLibrary(trustyInfos);
  }
  else{
    console.warn('Query trusty library infos failed!', result.data.toString());
  }

  return result;
}
